package junior.db.dao.base;

import com.google.common.collect.Lists;
import junior.util.value.ValueUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SqlValue {
    private List<Part> list;
    
    public static Part sqlPart(Object sql) {
        return new Part(sql, false);
    }
    
    public static Part argPart(Object sql) {
        return new Part(sql, true);
    }
    
    public String getSql() {
        if (list == null) {
            return "";
        }
        StringBuilder sql = new StringBuilder();
        for (Part part : list) {
            sql.append(part.isArg ? "?" : part.getVal());
        }
        return sql.toString();
    }
    
    public List<Object> getArgs() {
        List<Object> args = Lists.newArrayList();
        for (Part part : list) {
            if (part.isArg) {
                args.add(part.getVal());
            }
        }
        return args;
    }
    
    public SqlValue sql(Object sql) {
        prepareList();
        list.add(new Part(sql, false));
        return this;
    }
    public SqlValue arg(Object sql) {
        prepareList();
        list.add(new Part(sql, true));
        return this;
    }
    
    public SqlValue add(Part part) {
        prepareList();
        list.add(part);
        return this;
    }
    
    public SqlValue replace(Part oldOne, Part newOne) {
        list.set(list.indexOf(oldOne), newOne);
        return this;
    }
    
    private void prepareList() {
        if (list == null) {
            list = new ArrayList<>(2);
        }
    }
    
    public List<Part> getList() {
        return ValueUtils.ifNull(list, Collections.emptyList());
    }
    
    public static class Part {
        private Object val;
        private boolean isArg;
        protected Part(Object sql, boolean isArg) {
            this.val = sql;
            this.isArg = isArg;
        }
        public Object getVal() {
            return val;
        }
        public boolean isArg() {
            return isArg;
        }
    }
}
